#!/usr/bin/perl
my $packagePath = $ENV{PACKAGE_PATH};

my @pathItems = split(/\//, $packagePath);	
my $packageName = $pathItems[-1];

### Compare the versions of the package to be installed and the package already installed.
@currentVers = ExtractPkgVersion("$packagePath");
@receiptVers = ExtractPkgVersion("/Library/Receipts/" . $packageName);

my $EXIT_VALUE = 0;

### Don't allow to install if a higher version is already installed.
### The value 64 means we want to skip the package silently (no warning).
if ($currentVers[0] < $receiptVers[0]) 
{
	$EXIT_VALUE = 64;
}
elsif ($currentVers[0] == $receiptVers[0])
{
	if ($currentVers[1] < $receiptVers[1]) 
	{
		$EXIT_VALUE = 64;
	}
	elsif (($currentVers[1] == $receiptVers[1]) && ($currentVers[2] < $receiptVers[2]))
	{
		$EXIT_VALUE = 64;
	}
}

exit $EXIT_VALUE;

sub ExtractPkgVersion
{
	### Look for the plist in the package.
    my $path            = $_[0] . "/Contents/Info.plist";

    if (! -e $path) 
	{
		### Always allow to install if the package or its plist can't be found.
        return (0, 0, 0);
    }

    my $oldSeperator = $/;
    $/ = \0;

    open(PLIST, "$path") || do 
	{
        return (0, 0, 0);
    };

	### Parse the plist.
    $plistData = <PLIST>;
    $plistData =~ /<dict>(.*?)<\/dict>/gis;

    @items = split(/<key>/, $plistData);

	my %versiondata;

    shift @items;
    foreach $item (@items) 
	{
        $item =~ /(.*?)<\/key>.*?<string>(.*?)<\/string>/gis;
        $versiondata{ $1 } = $2;
    }

    close(PLIST);

    $/ = $oldSeperator;

 	### Get the version key from the plist and split the string into three numbers.
   	my $keyName         = "CFBundleShortVersionString";
	@versionItems = split(/\./, $versiondata{$keyName});
	
	return ($versionItems[0], $versionItems[1], $versionItems[2]);
}
